package com.bbcare.nutritious.plat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.JsonToEnetityUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.comm.ExcelUtil.ExcelUtil.ExcelExportData;
import com.bbcare.comm.ExcelUtil.FileDownloadUtils;
import com.bbcare.nutritious.plat.entity.PtCourseBespeak;
import com.bbcare.nutritious.plat.entity.PtCourseInfo;
import com.bbcare.nutritious.plat.service.ICourseService;

/**
 * pc课程控制器
 */
@Controller
@RequestMapping("/service/course")
public class PcCourseController {

    public static final Logger logger = Logger.getLogger(PcCourseController.class);

    @Autowired
    private ICourseService courseService;

    /**
     * 保存或修改课程信息
     */
    @ResponseBody
    @RequestMapping("/saveCourseInfo")
    public ResultModel<Object> saveCourseInfo(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in saveCourseInfo----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);

        //创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id
        courseInfo.setTenantId(tenantId);
        courseInfo.setActualNum(0);
        courseInfo.setState("1");
        //判空
        Map<String,Object> rspMap = courseService.saveCourseInfo(courseInfo);
        logger.debug("out saveCourseInfo----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 删除课程(修改课程状态为不可用)
     */
    @ResponseBody
    @RequestMapping("/delCourseInfo")
    public ResultModel<Object> delCourseInfo(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in delCourseInfo----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);
        if(courseInfo.getId()<=0){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "课程id不能为空！");
        }
        courseInfo.setState("2");
        Map<String,Object> rspMap = courseService.delCourseInfo(courseInfo);
        logger.debug("out delCourseInfo----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 分页查询课程信息
     */
    @ResponseBody
    @RequestMapping("/listCourseForPage")
    public Map<String, Object> listCourseForPage(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listCourseForPage----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);

        // 针对Datatable特殊处理
        String jsonStrtable = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStrtable)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStrtable);
            draw = jsonTable.getIntValue("draw");
            courseInfo.setStartNum(jsonTable.getIntValue("start"));
            courseInfo.setPageSize(jsonTable.getIntValue("length"));
        }
        //日期查询条件判断
        if(!StringUtils.isEmpty(courseInfo.getStartDate())){
        	if(StringUtils.isEmpty(courseInfo.getEndDate())){
        		logger.debug("查询课程时日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!courseInfo.getStartDate().equals(courseInfo.getEndDate()) && DateTimeUtil.compareDate(courseInfo.getStartDate(),courseInfo.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询课程时血糖日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        Map<String,Object> rspMap = courseService.listCourseInfoForPage(courseInfo);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
        	rspMap.put("draw", draw);
            rspMap.put("recordsTotal", rspMap.get("totalCount"));
            rspMap.put("recordsFiltered", rspMap.get("totalCount"));
        }
        //将查询条件返回
        //rspMap.put("param", weight);
        logger.debug("out listCourseForPage----arg=="+JSON.toJSONString(rspMap));
        return rspMap;
    }
    /**
     * 分页查询预约信息
     */
    @ResponseBody
    @RequestMapping("/listCourseBespeakForPage")
    public Map<String, Object> listCourseBespeakForPage(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listCourseForPage----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseBespeak courseBespeak = (PtCourseBespeak) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseBespeak.class);
        // 针对Datatable特殊处理
        String jsonStrtable = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStrtable)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStrtable);
            draw = jsonTable.getIntValue("draw");
            courseBespeak.setStartNum(jsonTable.getIntValue("start"));
            courseBespeak.setPageSize(jsonTable.getIntValue("length"));
        }
        Map<String,Object> rspMap = courseService.listCourseBespeakForPage(courseBespeak);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
        	rspMap.put("draw", draw);
            rspMap.put("recordsTotal", rspMap.get("totalCount"));
            rspMap.put("recordsFiltered", rspMap.get("totalCount"));
        }
        //将查询条件返回
        logger.debug("out listCourseForPage----arg=="+JSON.toJSONString(rspMap));
        return rspMap;
    }
    /**
     * 导出课程预约数据
     * @param request
     * @param jsonStr--日期段,userid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/exportCourseBespeak")
    public void exportCourseBespeak(HttpServletRequest request, PtCourseBespeak courseBespeak,HttpServletResponse response) throws Exception {
    	Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id
        if(StringUtils.isBlank(tenantId)){
        	logger.debug("租户id为空，请重新登录");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"租户id为空，请重新登录");
        }
        courseBespeak.setTenantId(tenantId);
        //查询要导出的预约数据
        List<PtCourseBespeak> list = courseService.listCourseBespeak(courseBespeak);;
        if(CollectionUtils.isEmpty(list)){
        	logger.debug("该时间段内无数据");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"无数据可供导出");
        }else{
        	for (int i = 0; i < list.size(); i++) {
        		list.get(i).setCreateTime(list.get(i).getCreateTime().substring(0,16));
        		if(list.get(i).getBespeakState()==1){
        			list.get(i).setBespeakStateStr("已预约");
        		}else if(list.get(i).getBespeakState()==2){
        			list.get(i).setBespeakStateStr("已取消");
        		}else{
        			list.get(i).setBespeakStateStr("已完成");
        		}

			}
        }
        //开始导出数据到Excel
        String fileName = "课程预约人员列表";
        //定义一个map集合 由于存取excel表格需要展示的数据信息
		LinkedHashMap<String, List<?>> map = new LinkedHashMap<String, List<?>>();
		map.put(fileName, list);
		List<String[]> fieldNames = new ArrayList<String[]>();
		fieldNames.add(new String[] { "persenName","phoneNo","taskNumber","courseName","lecturerName","joinNumber","createTime","bespeakStateStr","startTime","endTime","upperLimit","actualNum","hospitalName","hospitalAddress","specificAddress"  });
		//打印的excel表格 列名
		Map<String, String[]> moreColumns = new LinkedHashMap<String, String[]>();
		moreColumns.put("序号", new String[]{"序号"});

		moreColumns.put("预约人", new String[]{"预约人"});
		moreColumns.put("预留电话", new String[]{"预留电话"});
		moreColumns.put("预约编号", new String[]{"预约编号"});

		moreColumns.put("课程", new String[]{"课程"});
		moreColumns.put("讲师", new String[]{"讲师"});
		moreColumns.put("参加人数", new String[]{"参加人数"});

		moreColumns.put("预约时间", new String[]{"预约时间"});
		moreColumns.put("上课状态", new String[]{"上课状态"});
		moreColumns.put("课程开始时间", new String[]{"课程开始时间"});

		moreColumns.put("课程结束时间", new String[]{"课程结束时间"});
		moreColumns.put("课程预约人数上限", new String[]{"课程预约人数上限"});
		moreColumns.put("已预约人数", new String[]{"已预约人数"});

		moreColumns.put("医院名称", new String[]{"医院名称"});
		moreColumns.put("医院地址", new String[]{"医院地址"});
		moreColumns.put("详细地址", new String[]{"详细地址"});

		ExcelExportData setInfo = new ExcelExportData();
		setInfo.setDataMap(map);
		setInfo.setFieldNames(fieldNames);
		setInfo.setTitles(new String[] {fileName});
		//excel表格头部加入查询数据的日期起始值,电话,可以拼接其他的
		setInfo.setExportExcelDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));//设置导出日期
		setInfo.setMoreColumns(moreColumns);
		FileDownloadUtils.exportFile(request,response, setInfo, fileName);
    }

    /**
     * 导出课程数据
     */
    @RequestMapping(value="/exportCourseExcel")
    public void exportCourseExcel(HttpServletRequest request, PtCourseInfo courseInfo,HttpServletResponse response) throws Exception {
    	Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id
        if(StringUtils.isBlank(tenantId)){
        	logger.debug("租户id为空，请重新登录");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"租户id为空，请重新登录");
        }
        courseInfo.setTenantId(tenantId);
        //查询要导出的课程数据
        List<PtCourseInfo> list = courseService.listCourseInfoForAll(courseInfo);;
        if(CollectionUtils.isEmpty(list)){
        	logger.debug("无课程数据可导出");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"无课程数据可导出");
        }else{
        	for (int i = 0; i < list.size(); i++) {
        		list.get(i).setCreateTime(list.get(i).getCreateTime().substring(0,16));
			}
        }
        //开始导出数据到Excel
        String fileName = "课程列表";
        //定义一个map集合 由于存取excel表格需要展示的数据信息
		LinkedHashMap<String, List<?>> map = new LinkedHashMap<String, List<?>>();
		map.put(fileName, list);
		List<String[]> fieldNames = new ArrayList<String[]>();
		fieldNames.add(new String[] { "courseName","lecturerName","hospitalName","hospitalAddress","specificAddress","courseDate","startTime","endTime","courseIntroduce","actualNum","upperLimit"});
		//打印的excel表格 列名
		Map<String, String[]> moreColumns = new LinkedHashMap<String, String[]>();
		moreColumns.put("序号", new String[]{"序号"});
		moreColumns.put("课程名称", new String[]{"课程名称"});
		moreColumns.put("讲师名称", new String[]{"讲师名称"});

		moreColumns.put("医院名称", new String[]{"医院名称"});
		moreColumns.put("医院地址", new String[]{"医院地址"});
		moreColumns.put("详细地址", new String[]{"详细地址"});
		moreColumns.put("课程日期", new String[]{"课程日期"});
		moreColumns.put("课程开始时间", new String[]{"课程开始时间"});
		moreColumns.put("课程结束时间", new String[]{"课程结束时间"});
		moreColumns.put("课程介绍", new String[]{"课程介绍"});
		moreColumns.put("实际报名人数", new String[]{"实际报名人数"});
		moreColumns.put("报名人数上限", new String[]{"报名人数上限"});


		ExcelExportData setInfo = new ExcelExportData();
		setInfo.setDataMap(map);
		setInfo.setFieldNames(fieldNames);
		setInfo.setTitles(new String[] {fileName});
		//excel表格头部加入查询数据的日期起始值,电话,可以拼接其他的
		setInfo.setExportExcelDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));//设置导出日期
		setInfo.setMoreColumns(moreColumns);
		FileDownloadUtils.exportFile(request,response, setInfo, fileName);
    }
    /**
     * 通过条件查询用户
     */
    @ResponseBody
    @RequestMapping("/selectPatientByParamForCourse")
    public ResultModel<Object> selectPatientByParamForCourse(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
    	JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id
        if(StringUtils.isBlank(tenantId)){
        	logger.debug("租户id为空，请重新登录");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"租户id为空，请重新登录");
        }
        String userName = requestParam.getString("userName");
        String phoneNo = requestParam.getString("phoneNo");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);
        if(StringUtils.isNotBlank(userName)){
        	paramMap.put("userName", userName);
        }
        if(StringUtils.isNotBlank(phoneNo)){
        	paramMap.put("phoneNo", phoneNo);
        }
        Map<String,Object> rspMap = courseService.selectPatientByParamForCourse(paramMap);
        return new ResultModel<Object>(rspMap);
    }

    /**
     * 通过条件查询用户
     */
    @ResponseBody
    @RequestMapping("/getCourseForFourDayOfAllByUser")
    public ResultModel<Object> getCourseForFourDayOfAllByUser(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
    	JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id
        if(StringUtils.isBlank(tenantId)){
        	logger.debug("租户id为空，请重新登录");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"租户id为空，请重新登录");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);
        if(StringUtils.isBlank(courseInfo.getUserId())){
        	logger.debug("用户id不能为空");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"用户id不能为空");
        }
        courseInfo.setTenantId(tenantId);
        Map<String,Object> rspMap = courseService.getCourseForFourDayOfAll(courseInfo);
        return new ResultModel<Object>(rspMap);
    }
}
